package com.mao.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.mao.model.user.User;

public class SessionHelper {

	public static User getSessionUser() {
		HttpServletRequest request = null;
		HttpSession sess = null;
		if (ServletActionContext.getContext() != null) {
			request = ServletActionContext.getRequest();
		}
		if (request != null) {
			sess = request.getSession();
		} else {	//DWR调用
			WebContext wc = WebContextFactory.get();
			if (wc != null) {
				sess = wc.getSession();
			}
		}
		if (sess == null) {
			return null;
		}
		User user = (User) sess.getAttribute(SessionUser.SESSION_USE_KEY);
		return user;
	}

	public static void setUser(User user) {
		// 先设置 Session
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute(SessionUser.SESSION_USE_KEY, user);
	}

	public static String getCode() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(session.getAttribute("codeValue")!=null){
			return session.getAttribute("codeValue").toString();
		}
		return null;
	}
	
	public static HttpSession getSession() {
		HttpServletRequest request = null;
		HttpSession sess = null;
		if (ServletActionContext.getContext() != null) {
			request = ServletActionContext.getRequest();
		}
		if (request != null) {
			sess = request.getSession();
		} else {	//DWR调用
			WebContext wc = WebContextFactory.get();
			if (wc != null) {
				sess = wc.getSession();
			}
		}
		if (sess == null) {
			return null;
		}
		return sess;
	}

}
